import { localCache } from '@/utils/cache'
import { BASE_URL, TIME_OUT } from './config'
import DGRequest from './request'
import { LOGIN_TOKEN_KEY } from '@/global/constants'
import { useRouter } from 'vue-router'

const router = useRouter()

const dgRequest = new DGRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestSuccessFn: (config) => {
      // 每次请求都自动携带token
      const token = localCache.getCache(LOGIN_TOKEN_KEY)
      if (config.headers && token) {
        config.headers.Authorization = 'Bearer ' + token
      }
      return config
    },
    responseSuccessFn: (res) => {
      console.log('responseSuccessFn 响应成功拦截: ', res)
      // token过期，此时退出登录
      if (res.code === -1005) {
        console.log('退出登录')
        // 1.删除token
        localCache.removeCache(LOGIN_TOKEN_KEY)

        // 2.跳回登录页
        router.push('/login')
      }
      return res
    }
  }
})

export default dgRequest